package org.teachertools.web.struts;

import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;

public abstract class BaseActionForm extends ActionForm 
{
	private static final long serialVersionUID = 1L;

	protected Log log = LogFactory.getLog(getClass());
	
  	public abstract void reset();

    protected String getMessage(HttpServletRequest request, String key) {
        MessageResources messageResources = (MessageResources) request.getAttribute(Globals.MESSAGES_KEY);
        return messageResources.getMessage(key);
    }

	/**
	 * @see org.apache.struts.action.ActionForm#reset(org.apache.struts.action.ActionMapping, javax.servlet.http.HttpServletRequest)
	 */
	@Override
	public void reset(ActionMapping mapping, HttpServletRequest request)
	{
		super.reset(mapping, request);
		reset();
	}
	
	/**
	 * @see org.apache.struts.action.ActionForm#reset(org.apache.struts.action.ActionMapping, javax.servlet.ServletRequest)
	 */
	@Override
	public void reset(ActionMapping mapping, ServletRequest request)
	{
		super.reset(mapping, request);
		reset();
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public String toString()
	{
		try
        {
	        Map<String, Object> properties = BeanUtils.describe(this);
	        StringBuffer buffer = new StringBuffer();
	        Iterator<String> iterator = properties.keySet().iterator();
	        while (iterator.hasNext())
	        {
	            String key = iterator.next();
	            buffer.append(key).append('=').append(properties.get(key)).append('\n');
	        }
	        return buffer.toString();
        }
        catch (Exception e)
        {
	        return super.toString();
        }
	}
}